package org.dkakunsi.aplikasitoko.data.adapter;

import java.util.List;

import org.dkakunsi.aplikasitoko.data.access.KasirDataAccess;
import org.dkakunsi.aplikasitoko.data.entity.Kasir;
import org.dkakunsi.aplikasitoko.data.util.ApplicationDataException;
import org.dkakunsi.aplikasitoko.data.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.exception.ConstraintViolationException;

public class KasirDataAdapter implements KasirDataAccess {

	private Session session;
	private Transaction tx;
	
	public KasirDataAdapter() {
		this.session = HibernateUtil.openSession();
		this.tx = session.beginTransaction();
	}
	
	public KasirDataAdapter(Session session) {
		this.session = session;
		this.tx = session.beginTransaction();
	}
	
	@Override
	public void save(Object object) throws ApplicationDataException {
		Kasir kasir = null;
		
		try {
			kasir = (Kasir) object;
			
			session.save(kasir);
			tx.commit();
			} catch(ConstraintViolationException x) {
			throw new ApplicationDataException("Duplikasi data untuk KODE : " +kasir.getKode());
		}
	}

	@Override
	public void update(Object object)  throws Exception{
		Kasir kasir = (Kasir) object;
		
		session.merge(kasir);
		tx.commit();		
	}

	@Override
	public void delete(Object object)  throws Exception{
		Kasir kasir = (Kasir) object;
		
		session.delete(kasir);
		tx.commit();
	}

	@Override
	public Object getByID(String id) throws ApplicationDataException {
		Kasir kasir = (Kasir) session.get(Kasir.class, id);
		tx.commit();

		if(kasir != null){
			return kasir;
		} else {
			throw new ApplicationDataException("File Not Found");
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<org.dkakunsi.aplikasitoko.data.entity.Kasir> getAll() throws Exception {
		List<org.dkakunsi.aplikasitoko.data.entity.Kasir> all = null;
		
		all = session.createQuery("from Kasir order by KODE").list();

		return all;
	}
	
	@Override
	public Session getSession() {
		return this.session;
	}

	@Override
	public Object getBy(String nama) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}
}
